<?php
namespace Common\Model;

use Think\Model;

class ChannelModel extends  CommonModel {

	public $tableName = 'channel';

	public $status = [
		1 => '启用',
		2 => '禁用',
	];



	//查询渠道列表
	public function get_channel_list(array $params,$field="a.*",$is_page = true){
		$where = [];
		$pagesize = empty($params['pageSize']) ? '20' : $params['pageSize'];
		$params["channel_name"]?$where['a.channel_name'] = ["LIKE","%{$params['channel_name']}%"]:"";
		$params['status']?$where['a.status'] = $params['status']:"";
		$params['channel_number']?$where['a.channel_number'] = $params['channel_number']:"";
		if(isset($params['pid'])){
			$where['a.pid'] = $params['pid'];
		}
		if($is_page) {
			$count = $this
				->alias("a")
				->where($where)
				->join("LEFT JOIN tp_channel b ON b.id = a.pid")
				->count();
			$Page = new \Think\Page($count, $pagesize);
			$limit = $Page->firstRow . ',' . $Page->listRows;
		}else{
			$limit = "0,100000000";
		}


		$list = $this
			->alias("a")
			->field($field)
			->where($where)
			->join("LEFT JOIN tp_channel b ON b.id = a.pid")
			->order("a.id desc")
			->limit($limit)
			->select();
		int_to_string($list,['status'=>$this->status]);
		$data = [
			'count' => $is_page?$count:count($list),
			'list'  => $list
		];
		return $data;
	}




	//添加/修改渠道
	public function channel_save(array $params){
		$where = [
			'channel_name' => $params['channel_name'],
			'pid'		   => $params['pid']
		];
		if($params['channel_id']){
			$where['id'] = ['neq',$params['channel_id']];
		}
		$info = $this->where($where)->find();
		if($info) return $this->returnData("渠道名称已存在,请重新输入");
		$data = [
			'channel_name'   => $params['channel_name'],
			'pid'  			 => $params['pid']?$params['pid']:0,
			'status'     	 => $params['status'],
		];
		if($params['channel_id']){
			if($params['pid'] && $params['status'] == 1){
				$pid_info = $this->where(['id'=>$params['pid']])->find();
				if($pid_info['status'] == 2)  return $this->returnData("上级渠道已禁用,不允许启用该渠道");
			}

			if($data['pid'] == 0 && $params['status'] == 2){		//一级禁用，二级也全部禁用
				$condition = ['pid' => $params['channel_id']];
				$sub_data  = ['update_time' => time(), 'update_by'   => $params['userId'], 'status' => 2];
				$this->where($condition)->save($sub_data);
			}

			$data['update_time'] = time();
			$data['update_by'] = $params['userId'];
			$result = $this->where(['id'=>$params['channel_id']])->save($data);


		}else{
			$data['create_time'] = time();
			$data['create_by'] = $params['userId'];
			$result = $this->add($data);
		}
		return $this->returnData($result?"设置成功":"设置失败",$result?200:500);
	}





}

?>
